<template>
  <div>
    <myDivider name="菜单管理"></myDivider>
    <div style="margin-left: 20px;" class="Top">
      <el-input style="width: 200px;" maxlength="20" v-model="query.title" placeholder="菜单标题"
        @keyup.enter.native="SouSuo" clearable></el-input>
      <el-input style="width: 200px;" maxlength="70" v-model="query.url" placeholder="菜单路径" @keyup.enter.native="SouSuo"
        clearable></el-input>
      <el-button type="primary" style=" margin-left: 15px" @click="SouSuo">查询</el-button>
      <el-button style=" margin-left: 15px" @click="reset">重置</el-button>
      <div style="margin-top: 10px;">
        <el-button type="primary" @click="openForm">新增</el-button>
      </div>
    </div>
    <div class="popTableStyle">
      <el-table :data="menuData" style="width: 100%" class="menuTable" row-key="id" ref="tableRef"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @select="rowSelect" @select-all="selectAll">
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <el-table-column prop="title" label="菜单标题">
        </el-table-column>
        <el-table-column prop="url" label="菜单路径" align="center">
        </el-table-column>
        <el-table-column prop="icon" label="icon" align="center">
          <template slot-scope="scope">
            <!-- <div>{{scope.row.icon}}</div> -->
            <i :class="scope.row.icon"></i>
            <!-- <svg-icon :icon-class="scope.row.icon" /> -->
          </template>
        </el-table-column>
        <el-table-column prop="level" label="等级" align="center"> </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <!-- <el-button type="primary" icon="el-icon-edit" circle size="mini"
              @click="echoValueForUpdate(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle size="mini"
              @click="deleteMenuById(scope.row)"></el-button>
            <el-button type="text" icon="el-icon-sort-up" @click="moveUp(scope.row)"></el-button>
            <el-button type="text" icon="el-icon-sort-down" @click="moveDown(scope.row)"></el-button> -->
            <div class="textBtn">
              <el-row>
                <el-col class="el" :span="6">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="echoValueForUpdate(scope.row)">编辑</span>
                </el-col>
                <el-col class="el" :span="6">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="deleteMenuById(scope.row)">删除</span>
                </el-col>
                <el-col class="el" :span="6">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;" @click="moveUp(scope.row)">上移</span>
                </el-col>
                <el-col class="el" :span="6">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;" @click="moveDown(scope.row)">下移</span>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog width="500px" :title="insertForm.insertType === 0 ? '添加菜单' : '修改菜单'" :visible.sync="dialogFormVisible">
      <el-form :model="insertForm" :rules="insertRules" ref="insertForm">
        <el-form-item label="菜单类型：" :label-width="formLabelWidth" class="formItemStyle">
          <el-radio-group v-model="insertForm.type" @change="menuTypeChange" :disabled="insertForm.typeDisable">
            <el-radio label="menu">菜单</el-radio>
            <el-radio label="folder">目录</el-radio>
            <el-radio label="button">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="insertForm.type == 'button' ? '按钮名称：' : '菜单名称：'" :label-width="formLabelWidth"
          class="formItemStyle" prop="title">
          <el-input maxlength="20" v-model="insertForm.title" autocomplete="off" style="width: 262px"></el-input>

        </el-form-item>

        <el-form-item v-if="insertForm.type != 'button'" label="菜单路径：" :label-width="formLabelWidth"
          class="formItemStyle">
          <el-input maxlength="70" v-model="insertForm.url" autocomplete="off" style="width: 262px"
            :disabled="insertForm.urlDisable"></el-input>
        </el-form-item>

        <el-form-item v-if="insertForm.type == 'button'" prop="" required label="按钮功能：" :label-width="formLabelWidth"
          class="formItemStyle">
          <el-input maxlength="20" v-model="insertForm.url" autocomplete="off" style="width: 262px"
            :disabled="insertForm.urlDisable"></el-input>
        </el-form-item>


        <el-form-item v-if="insertForm.type != 'button'" label="父级目录：" :label-width="formLabelWidth"
          class="formItemStyle">
          <div class="block">
            <el-cascader v-model="insertForm.pids" placeholder="试试搜索：系统目录" :options="fatherMenuData" filterable
              :disabled="insertForm.fatherDisable" :props="{ value: 'id', label: 'title', checkStrictly: true }"
              clearable></el-cascader>
          </div>
        </el-form-item>
        <el-form-item v-if="insertForm.type == 'button'" label="父级菜单：" :label-width="formLabelWidth"
          class="formItemStyle" prop="" required>
          <div class="block">
            <el-cascader v-model="insertForm.pids" placeholder="试试搜索：系统目录" :options="fatherMenuData" filterable
              :disabled="insertForm.fatherDisable" :props="{ value: 'id', label: 'title', checkStrictly: true }"
              clearable></el-cascader>
          </div>
        </el-form-item>

        <el-form-item :label="insertForm.type == 'button' ? '按钮图标：' : '菜单图标：'" :label-width="formLabelWidth"
          class="formItemStyle">
          <e-icon-picker v-model="insertForm.iconName" style="width:57% " />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="insertForm.typeDisable == false" type="primary" @click="insertMenuAndCloseForm('insertForm')">确
          定</el-button>
        <el-button v-if="insertForm.typeDisable" type="primary" @click="updateMenuAndCloseForm('insertForm')">确
          定</el-button>

      </div>

    </el-dialog>
    <div class="pageFooterFather">
      <!-- <el-pagination v-if="totalSize > pageSize" background layout="prev, pager, next" :total="totalSize"
        @current-change="handleCurrentChange" class="pageFooter">
      </el-pagination> -->
      <myPagination :pageNum="pageNum" :total="totalSize" @PageChange="PageChange" @pageSizeChange="pageSizeChange">
      </myPagination>
    </div>
  </div>
</template>



<script>
import {
  getMenuList,
  insertMenu,
  getFatherMenuList,
  deleteMenuById,
  ifHasSonMenus,
  getMenuById,
  updateMenu,
  menuMoveUp,
  menuMoveDown
} from "./menu";
// import Menu from "./indexedDB.vue"
import call from "./siblingCall";
export default {
  data() {
    return {
      menuData: [], //菜单原始数据
      fatherMenuData: [], //弹框中的父级选项
      query: {
        //左上角查询input
        title: "",
        url: "",
      },
      insertForm: {
        // 新增弹框参数
        pid: "",
        title: "",
        url: "",
        type: "menu",
        urlDisable: false,
        iconName: "",
        id: 0,
        pids: [], //新增窗口父级菜单选项的默认值,
        typeDisable: false,
        insertType: 0,
        fatherDisable: false
      },
      insertRules: {
        title: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur",
          },
        ],

      },
      dialogFormVisible: false, //控制弹框开关
      formLabelWidth: "120px", //控制前面label的宽度
      pageNum: 1,
      pageSize: 10,
      totalSize: 0,
      totalPage: 0,
      rowBrothersData: [],
    };
  },
  activated: function () {

    this.$set(this.query, 'title', '')
    this.$set(this.query, 'url', '')
    //刚进入页面加载
    getMenuList(this.query.title, this.query.url, this.pageNum, this.pageSize).then((res) => {
      console.log(res, '菜单管理列表数据');
      this.menuData = res.list;
      // this.pageNum = res.pageNum;
      // this.pageSize = res.pageSize;
      this.totalSize = res.total;
      this.totalPage = res.pages;


    });
    getMenuList('', '', 1, 10000).then((res) => {

      console.log(res, 'getFatherMenuList')
      this.fatherMenuData = res.list;

    });

  },


  methods: {
    PageChange(e) {//分页器——页数变化
      this.pageNum = e
      this.queryMenuList()
    },
    pageSizeChange(e) { //分页器——每页数量变化
      this.pageNum = 1
      this.pageSize = e
      this.queryMenuList()
    },
    SouSuo() {
      this.pageNum = 1
      this.queryMenuList()
    },
    reset() {
      this.$set(this.query, 'title', '')
      this.$set(this.query, 'url', '')
      this.pageNum = 1
      this.queryMenuList()
    },
    //按条件查询菜单列表
    queryMenuList() {
      getMenuList(
        this.query.title,
        this.query.url,
        this.pageNum,
        this.pageSize
      ).then((res) => {
        if (res.list.length < 1 && this.pageNum != 1) { //判断，当搜索关键字有内容时，我直接点击分页，会造成关键词列表中没有某某页的数据，那么我就用第一页重新请求一次
          this.pageNum = 1
          this.queryMenuList()
          return
        }
        this.menuData = res.list;

        this.totalSize = res.total;
        this.totalPage = res.pages;
      });
    },
    moveUp(row) {
      menuMoveUp(row.id).then((res) => {
        if (res.data.code != 200) {
          this.$message(res.data)
        } else {
          this.queryMenuList();
          call.$emit('getAllMenuList');
        }
      });


    },

    moveDown(row) {
      menuMoveDown(row.id).then((res) => {
        if (res.data.code != 200) {
          this.$message(res.data)
        } else {
          this.queryMenuList();
          call.$emit('getAllMenuList');
        }
      });
    },


    // 修改选中状态
    toggleSelection(rows, flag) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.tableRef.toggleRowSelection(row, flag)
        })
      } else {
        this.$refs.tableRef.clearSelection()
      }
    },

    // 选择行
    rowSelect(selection, row) {
      console.log(selection, row, selection.indexOf(row), this.menuData);
      if (this.chooseNum == 'one') { // 单选
        // selection.indexOf(row)为-1则是取消，其他则为选中
        if (selection.length > 0) {
          for (let i = 0; i < selection.length; i++) {
            if (selection[i].children) {
              var isOne = false
              selection[i].children.filter(item => {
                if (item.uuid == row.uuid) { // 当前选中的子和已选的是同一个父
                  isOne = true
                }
              })
              if (!isOne) {
                this.$refs.tableRef.clearSelection()
                this.$refs.tableRef.toggleRowSelection(row, true)
              }
            }
          }
        }
      }
      // selection.indexOf(row)为-1则是取消，其他则为选中
      // 选中父,则所有的子也被选中
      if (selection.indexOf(row) > -1 && row.children) {
        this.toggleSelection(row.children, true);
      }
      // 取消父,则所有的子也被取消
      if (selection.indexOf(row) === -1 && row.children) {
        this.toggleSelection(row.children, false);
      }
      // 选中子，父也被选中
      if (selection.indexOf(row) > -1 && !row.children) {
        for (let i = 0; i < this.menuData.length; i++) {
          this.menuData[i].children.filter(item => {
            if (item.id === row.id) {
              this.$refs.tableRef.toggleRowSelection(this.menuData[i], true)
            }
          });
        }
      }
      // 取消子，父的子如果全被取消，父也被取消
      if (selection.indexOf(row) === -1 && !row.children) {
        var k = -1, isAllChoose = false
        // 找到父组件
        for (let i = 0; i < this.menuData.length; i++) {
          this.menuData[i].children.filter(item => {
            if (item.id === row.id) {
              k = i
            }
          });
        }
        for (let j = 0; j < this.menuData[k].children.length; j++) {
          // 当前的父 还有子没被取消
          if (selection.indexOf(this.menuData[k].children[j]) != -1) {
            isAllChoose = true
          }
        }
        if (!isAllChoose) {
          this.$refs.tableRef.toggleRowSelection(this.menuData[k], false)
        }
      }
    },

    // 全选
    selectAll(selection) {
      var flag = false; // 默认 为全不选
      selection.forEach(item => {
        if (item.children) {
          flag = true;
          this.toggleSelection(item.children, true);
        }
      });
      if (!flag) {
        this.toggleSelection();
      }
    },



    //=================

    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.queryMenuList();
    },

    //弹出弹框并加载父级菜单
    openForm(type) {
      getMenuList('', '', 1, 10000).then((res) => {

        console.log(res, 'getFatherMenuList')
        this.fatherMenuData = res.list;

      });
      if (type == "update") {
        this.insertForm.typeDisable = true;
        this.insertForm.insertType = 1;
        this.insertForm.fatherDisable = true;
      } else {
        this.resetField();
        this.insertForm.type = "menu";
        this.insertForm.insertType = 0;
        this.insertForm.typeDisable = false;
        this.insertForm.fatherDisable = false;
      }
      if (this.insertForm.type == "folder") {
        this.insertForm.urlDisable = true
      } else {
        this.insertForm.urlDisable = false
      }

      this.$nextTick(() => {
        this.$refs.insertForm.clearValidate()
      })
    },
    //新增菜单并关闭弹框
    insertMenuAndCloseForm(insertForm) {
      if (this.insertForm.type == 'button' && !this.insertForm.url) {
        this.$message.error('请输入按钮功能')
        return
      }
      if (this.insertForm.type == 'button' && this.insertForm.pids.length == 0) {
        this.$message.error('请选择父级菜单')
        return
      }
      var flag = true;
      this.$refs[insertForm].validate((valid) => {
        if (!valid) {
          flag = false;
          return false;
        }
      });
      if (!flag) {
        return;
      }

      if (this.insertForm.pids != null && this.insertForm.pids.length != 0) {
        this.insertForm.pid = this.insertForm.pids[this.insertForm.pids.length - 1];
      } else {
        this.insertForm.pid = 0
      }

      insertMenu(
        this.insertForm.pid,
        this.insertForm.title,
        this.insertForm.url,
        this.insertForm.type,
        this.insertForm.iconName,
        this.insertForm.pids,
      ).then((res) => {
        if (res.data.code == 200) {
          this.$message({
            message: "添加成功",
            type: "success",
          });
          this.dialogFormVisible = false;
          this.queryMenuList();
          call.$emit('getAllMenuList');
        } else {
          this.$message({
            message: res.data.message,
            type: "warning",
          });
        }
      });
    },
    deleteMenuById(row) {
      var id = row.id;
      ifHasSonMenus(id).then((res) => {
        if (res.data.hasChildren == true) {
          this.$confirm("目录下子菜单将同时删除, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.deleteMenu(id);
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
              return;
            });
        } else {
          this.$confirm("确认删除该菜单吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.deleteMenu(id);
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
              return;
            });
        }
      });
    },
    deleteMenu(id) {
      deleteMenuById(id).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          call.$emit('getAllMenuList');
          this.queryMenuList();
        } else {
          this.$message({
            message: res.message,
            type: "warning",
          });
        }
      });
    },
    menuTypeChange() {
      this.resetField();
      if (this.insertForm.type == "folder") {
        this.insertForm.urlDisable = true;
      } else {
        this.insertForm.urlDisable = false;
      }
    },
    echoValueForUpdate(row) {


      var id = row.id;
      getMenuById(id).then((res) => {
        var menu = res.data;
        console.log(menu)
        var pids = eval('(' + menu.pids + ')');
        this.resetField();
        this.insertForm.iconName = menu.icon;
        this.insertForm.title = menu.title;
        this.insertForm.id = menu.id;
        this.insertForm.url = menu.url;
        this.insertForm.type = menu.type;
        this.insertForm.pids = pids;

        this.openForm("update");
      });
    },
    resetField() {
      this.insertForm.pids = [];
      this.dialogFormVisible = true;
      this.insertForm.iconName = "";
      this.insertForm.title = "";
      this.insertForm.id = 0;
      this.insertForm.url = "";
    },
    updateMenuAndCloseForm(insertForm) {
      if (this.insertForm.type == 'button' && !this.insertForm.url) {
        this.$message.error('请输入按钮功能')
        return
      }
      if (this.insertForm.type == 'button' && this.insertForm.pids.length == 0) {
        this.$message.error('请选择父级菜单')
        return
      }
      var flag = true;
      this.$refs[insertForm].validate((valid) => {
        if (!valid) {
          flag = false;
          return false;
        }
      });
      if (!flag) {
        return;
      }
      if (this.insertForm.pids != null) {
        this.insertForm.pid = this.insertForm.pids[this.insertForm.pids.length - 1];
      }
      if (this.insertForm.pid == undefined) {
        this.insertForm.pid = 0;
      }
      updateMenu(
        this.insertForm.id,
        this.insertForm.pid,
        this.insertForm.title,
        this.insertForm.url,
        this.insertForm.type,
        this.insertForm.iconName,
        this.insertForm.pids
      ).then((res) => {
        if (res.data.code == 200) {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.dialogFormVisible = false;
          this.queryMenuList();
          call.$emit('getAllMenuList');
        } else {
          this.$message({
            message: res.data.message,
            type: "warning",
          });
        }
      });


    }


  },
};
</script>
<style lang="less" scoped>
.popTableStyle {
  /deep/ .el-table {
    .has-gutter {
      .is-leaf {
        background-color: #efefef;
      }
    }

    .el-table__row:not([class*="el-table__row--level-"]) {
      td:first-child {
        padding-left: 24px !important; //一级数据无Child缩进
      }
    }

    .el-table__placeholder {
      margin-left: 3px; //子节点无Child缩进
    }

    .el-table__body tr.current-row>td.el-table__cell {
      background-color: #409eff;

      .cell {
        color: white;
        font-weight: 600;
      }
    }
  }
}

.textBtn {
  position: relative;

  /deep/ .el-row {
    display: flex;
    justify-content: center;
  }

  .el {
    display: block;
    position: relative;

    &:nth-child(n+2) {


      &::after {
        position: absolute;
        left: -1px;
        top: 50%;
        content: '';
        width: 2px;
        transform: translateY(-50%) scale(0.5, 1);
        height: 10px;
        background-color: #aaa;
      }
    }
  }
}

.Top {
  position: relative;

  .operation {
    position: absolute;
    left: 15px;
    top: 68px;
  }
}

.menuTable {
  margin-top: 100px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}





.operation {
  margin-right: 50px;
  float: right;
  margin-top: 20px;
}

/* .formStyle {
  width: 1300px;
  margin: 20px auto;
} */

.formItemStyle {
  margin-bottom: 22px;
  margin-left: 22px;
}

.pageFooter {
  margin-top: 3%;
  margin-left: 40%;
}

.pageFooterFather {
  top: 84%;
  position: relative;
  width: 100%;
}

.el-cascader-menu {
  height: fit-content;
  width: fit-content;
}
</style>